import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    FlatList,
    StatusBar,
    TextInput,
    ScrollView,
    Picker,
    WebView,
    DeviceEventEmitter
} from 'react-native';
import { base } from "../../../../assets/style";
import LinearGradient from "react-native-linear-gradient";
import ReactNativePickerSelect from 'react-native-picker-select'
import Toast from 'react-native-easy-toast'
import Loading from '../../../../components/loading/index'
import { API } from "../../../../api";
import { getUserInfo } from "../../../../utils/login";
import { i18n } from "../../../../utils/locales/i18n";
import {EMAIL_REG_EXP, geetestURL_8080, PHONE_REGEXP_HK, PHONE_REGEXP_ZH} from "../../../../config";

type Props = {};
export default class VerifyEmail extends Component<Props> {
    static navigationOptions = ({ navigation }) => {
        return {
            title: i18n.t('info32'),
            headerStyle: {
            },
            headerTintColor: '#0f0f0f',
            headerBackTitle: null
        }
    };
    constructor() {
        super();
        this.state = {
            email: '',
            messageCode: '',
            district: '',
            geetestVisible: false,
            isSend: false,
            second: 60,
            showLoading: false,
            info: ''
        }
    }

    // 获取验证码
    getVerifyCode = async () => {
        if (this.state.email === '') {
            this.refs.toast.show(i18n.t('i33'))
            return
        }
        if (!EMAIL_REG_EXP.test(this.state.email)) {
            this.refs.toast.show(i18n.t('i241'))
            return
        }
        // 检测邮箱是否已经注册过，有则不让注册
        const vRes = await API.checkEmail({email: this.state.email})
        if (vRes.code === 10004) {
            this.refs.toast.show(vRes.msg || i18n.t('i239'))
            return
        }
        this.setState({
            geetestVisible: true
        })
    }
    // webview加载失败处理
    onGeetestError = () => {
        this.setState({
            geetestVisible: false
        })
        alert('Geetest faild!')
    }
    // 处理极验返回的消息
    handleGeetestMessage = (e) => {
        e.persist();
        if (e.nativeEvent.data === 'send') {
            // 成功发送，隐藏webview
            setTimeout(() => {
                this.setState({
                    geetestVisible: false,
                    isSend: true
                })
                // 重新发送倒计时
                const timer = setInterval(() => {
                    this.setState({
                        second: this.state.second - 1
                    })
                    if (this.state.second <= 0) {
                        clearInterval(timer)
                        this.setState({
                            second: 60,
                            isSend: false
                        })
                    }
                }, 1000)
            }, 0)
        }
    }
    // 向极验webview 发送数据
    sendMessageToGeetest = () => {
        // type: 1注册 2绑定 3设置 4重置登陆密码 5重置资金密码 6提币验证码
        let options = {
            to: this.state.email,
            type: 2
        }
        this.refs.webview.postMessage(JSON.stringify(options))
    }
    // 提交
    bindEmail = async () => {
        if (!this.state.email || !this.state.messageCode) {
            this.refs.toast.show(i18n.t('plz_cpl'))
            return
        }
        this.setState({
            showLoading: true,
            info: i18n.t('loading')
        })


        const res = await API._fetch('bindEmail', {
            'email': this.state.email,
            'captcha': this.state.messageCode
        })
        this.setState({
            showLoading: false,
            info: ''
        })
        if (res.code === 10000) {
            this.setState({
                showLoading: false,
                info: ''
            })
            this.refs.toast.show(i18n.t('o_success'))
            setTimeout(() => {
                DeviceEventEmitter.emit('refresh_user_info');
                this.props.navigation.goBack()
            }, 0)
        } else {
            this.setState({
                showLoading: false,
                info: ''
            })
            this.refs.toast.show( res.msg || i18n.t('o_defeat'))
        }
    }
    render() {
        return (
            <View style={[base.flex_1]}>
                { this.state.showLoading ? (
                    <Loading
                        info={this.state.info}
                    />
                ) : null}
                <Toast ref={'toast'} position={'bottom'} positionValue={200}/>
                {/*极验验证 */}
                { this.state.geetestVisible ? (
                    <View style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 999 }}>
                        <WebView
                            ref={'webview'}
                            onMessage={ msg => this.handleGeetestMessage(msg)}
                            onLoad={this.sendMessageToGeetest}
                            bounces={false}
                            javaScriptEnabled={true}
                            onError={this.onGeetestError}
                            style={{ flex: 1 }}
                            // source={require('../../../../pages/geetest_8080.html')}
                            source={{uri: geetestURL_8080}}
                        />
                    </View>
                ) : null}
                <View style={[base.flex_1, base.bg_gray, base.content_container]}>
                    <View style={{paddingHorizontal: 15, paddingBottom: 20, backgroundColor: '#fff', alignItems: 'center', marginTop: 10, borderRadius: 5 }}>
                        <View>
                            <Image style={{width: 200, height: 200}} resizeMode={'contain'} source={require('@images/mine/verify_email.png')}/>
                        </View>
                        {/*<View style={[base.flex_row_between, { marginVertical: 5, height: 45, width: '100%', borderRadius: 5, borderWidth: 1, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>*/}
                        {/*<Text style={[base.color_gray]}>(+86) China</Text>*/}
                        {/*<TouchableOpacity style={[base.flex_1, base.flex_row_end, { height: '100%' }]}>*/}
                        {/*<Image resizeMode={'contain'} style={{width: 10, height: 10}} source={require('@images/mine/icon_triangle.png')}/>*/}
                        {/*</TouchableOpacity>*/}
                        {/*</View>*/}
                        <View style={[base.flex_row_between, { marginVertical: 5, height: 45, width: '100%', borderRadius: 5, borderWidth: 1, borderColor: '#d2d2d2', paddingHorizontal: 15 }]}>
                            <TextInput
                                style={[base.color_gray, {width: '100%'}]}
                                value={this.state.email}
                                onChangeText={(text) => this.setState({email: text})}
                                placeholder={i18n.t('i34')}
                            />
                        </View>
                        <View style={{ height: 45, width: '100%', borderColor: '#d2d2d2', borderWidth: 1, borderRadius: 5, marginVertical: 10, flexDirection: 'row' }}>
                            <TextInput
                                style={{color: '#808080', width: '100%', height: '100%', flex: 1, paddingLeft: 15, borderRightColor: '#d2d2d2', borderRightWidth: 1}}
                                onChangeText={(text) => this.setState({messageCode: text})}
                                placeholder={i18n.t('m_message')}
                                value={this.state.messageCode}
                            />
                            { this.state.isSend ? (
                                <TouchableOpacity style={{width: 100, height: '100%'}}>
                                    <View style={[base.flex_1, base.flex_row_center]}>
                                        <Text style={[base.color_gray, {fontSize: 12}]}>
                                             {this.state.second} s
                                        </Text>
                                    </View>
                                </TouchableOpacity>
                            ) : (
                                <TouchableOpacity onPress={this.getVerifyCode} style={{width: 100, height: '100%'}}>
                                    <View style={[base.flex_1, base.flex_row_center]}>
                                        <Text style={[base.color_orange, {fontSize: 16}]}>
                                            {i18n.t('cag')}
                                        </Text>
                                    </View>
                                </TouchableOpacity>
                            )}

                        </View>
                    </View>
                    <View style={[base.flex_1, base.flex_col_center, { paddingBottom: 30 }]}>
                        <TouchableOpacity style={{width: '100%'}} onPress={this.bindEmail}>
                            <LinearGradient
                                start={{x: 0, y: 0}}
                                end={{x: 1, y: 1}}
                                colors={['#feac1c', '#ff7506']}
                                style={{ width: '100%', height: 46, borderRadius: 23, justifyContent: 'center', alignItems: 'center' }}
                            >
                                <Text style={{color: '#fff', fontSize: 16}}>{i18n.t('save')}</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    </View>
                    {/*<Picker*/}
                    {/*selectedValue={this.state.district}*/}
                    {/*style={{ height: 200, width: '100%' }}*/}
                    {/*onValueChange={(itemValue, itemIndex) => this.setState({district: itemValue})}>*/}
                    {/*<Picker.Item label="(+86) China" value="+86" />*/}
                    {/*<Picker.Item label="(+852) Hong Kong" value="+852" />*/}
                    {/*</Picker>*/}
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
});
const pickerSelectStyles = StyleSheet.create({
    inputIOS: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 45,
        paddingHorizontal: 15,
        borderWidth: 1,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        backgroundColor: 'white',
        color: '#808080',
        marginVertical: 5
    },
    inputAndroid: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 45,
        paddingHorizontal: 15,
        borderWidth: 1,
        borderColor: '#d2d2d2',
        borderRadius: 5,
        backgroundColor: 'white',
        color: '#808080',
        marginVertical: 5
    },
});
